package com.shop.common.util;

import com.alibaba.fastjson.JSON;
import com.shop.common.model.ServiceBean;
import com.shop.common.util.state.AccountType;
import com.shop.common.util.state.KeyPrefix;
import com.shop.common.util.tmpl.IDValiBean;
import com.shop.common.util.tmpl.SmsBean;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

/**
 * @Description: 验证码发送工具
 *
 * @author zhoulk
 * @date: 2019年03月28日  13:21
 */

public class SendCodeUtil {

    private static RedisUtil redisUtil = new RedisUtil("127.0.0.1", 6379);
    private static Properties SMS_PROP = new Properties();

    static {
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream("smsconfig.property");
            BufferedReader bf = new BufferedReader(new InputStreamReader(in));
            SMS_PROP.load(bf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static ServiceBean SEN_CODE(AccountType accountType, KeyPrefix keyPrefix, String phone) {
        ServiceBean serviceBean = new ServiceBean();
        String key = KeyPrefix.TTL.value() + keyPrefix.value() + phone;
        Boolean flag = redisUtil.exists(key);
        if (flag) {
            Long hisTime = redisUtil.ttl(key);
            if (hisTime > 0) {
                serviceBean.setSuccess(false);
                serviceBean.setMsg("验证码已发送，请勿重复操作");
                serviceBean.setTtl(hisTime);
                return serviceBean;
            }
        }
        String code = String.valueOf(new Random().nextInt(8000) + 1234);//生成一个随机码
        switch (accountType) {
            case EMAIL:
                flag = SEND_EMAIL(code, phone);
                break;
            case PHONE:
                flag = SEND_SMS(code, phone);
                break;
            default:
                serviceBean.setSuccess(false);
                serviceBean.setMsg("请选择正确的类型");
                return serviceBean;
        }
        if (!flag) {
            serviceBean.setMsg("验证码发送失败，请重试");
        } else {
            redisUtil.set(key, "", 59);
            key = keyPrefix.value() + phone;
            redisUtil.set(key, code, 60 * 5);
            serviceBean.setMsg("验证码已发送，请注意查收");
        }
        serviceBean.setSuccess(flag);
        return serviceBean;
    }

    public static ServiceBean SEND_BY_EMAIL(KeyPrefix keyPrefix, String email) {
        ServiceBean serviceBean = new ServiceBean();
        if (StringUtils.isBlank(email)) {
            serviceBean.setSuccess(false);
            serviceBean.setMsg("邮箱不能为空");
            return serviceBean;
        }
        return SEN_CODE(AccountType.EMAIL, keyPrefix, email);
    }

    public static ServiceBean SEND_BY_PHONE(KeyPrefix keyPrefix, String phone) {
        ServiceBean serviceBean = new ServiceBean();
        if (StringUtils.isBlank(phone)) {
            serviceBean.setSuccess(false);
            serviceBean.setMsg("手机号不能为空");
            return serviceBean;
        }
        return SEN_CODE(AccountType.PHONE, keyPrefix, phone);
    }

    /**
     * @Function com.shop.common.util.SendCodeUtil.VALIDATE_CODE
     * @Description //TODO 校验验证码
     *
     * @param: keyPrefix 验证码类型
     * @param: account 账号
     * @param: code 验证码
     * @return boolean 结果
     * @errorCode //TODO
     *
     * @Author zhoulk
     * @Date 2019/3/29 13:15
     *
     **/
    public static boolean VALIDATE_CODE(KeyPrefix keyPrefix, String account, String code) {
        ServiceBean serviceBean = new ServiceBean();
        String key = keyPrefix.value() + account;
        boolean flag = redisUtil.exists(key);
        if (flag) {
            String real = redisUtil.get(key);
            flag = real.equals(code);
        }
        if (flag) {
            redisUtil.del(key);
        }
        return flag;
    }

    public static boolean SEND_SMS(String content, String mobile) {
        String host = SMS_PROP.getProperty("host"); ////https://dxyzm.market.alicloudapi.com"
        String path = SMS_PROP.getProperty("path");
        String method = SMS_PROP.getProperty("method");
        String appcode = SMS_PROP.getProperty("appcode");
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("content", "【闲卖网】验证码为：" + content + "，5分钟内有效！");
        System.out.println(querys.get("content"));
        querys.put("mobile", mobile);
        Map<String, String> bodys = new HashMap<>();
        SmsBean s;
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            s = JSON.parseObject(EntityUtils.toString(response.getEntity()), SmsBean.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if ("Success".equals(s.getReturnStatus())) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean SEND_EMAIL(String conten, String addr) {

        return false;
    }

    public static ServiceBean VALIDATE_IDCARD(String idCard, String mobile, String name) {
        ServiceBean serviceBean = new ServiceBean();
        String host = "https://checkphone.market.alicloudapi.com";
        String path = "/carrieroperator";
        String method = "GET";
        String appcode = "73951da6b5ca4049b1acd262d0a9cd60";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("idCard", idCard);// !!! 请求参数 身份证号码
        querys.put("mobile", mobile);// !!! 请求参数 电话号码
        querys.put("name", name); // !!! 请求参数 姓名
        IDValiBean valiBean = new IDValiBean();
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            valiBean = JSON.parseObject(EntityUtils.toString(response.getEntity()), IDValiBean.class);
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("01".equals(valiBean.getStatus())) {
            serviceBean.setSuccess(true);
        } else {
            serviceBean.setSuccess(false);
            serviceBean.setMsg(valiBean.getMsg());
        }
        return serviceBean;

    }
}
